package handle

import (
    "rpcserver/service/rpcservice"
    "fmt"
)

/*
type ProtoRpcService interface {
	// Parameters:
	//  - Msg
	ServeTwoWayMessage(msg *ProtoRequest) (r *ProtoResponse, err error)
	// Parameters:
	//  - Msg
	ServeOneWayMessage(msg *ProtoRequest) (err error)
}
*/

type Handle1Func func(content []byte)(ret int32)
type Handle2Func func(content []byte)(retctx []byte, retcode int32)

type SvHandle struct {
    OneWayFunc map[int32] Handle1Func
    TwoWayFunc map[int32] Handle2Func
}

func NewSvHandle() *SvHandle {
    h := &SvHandle{make(map[int32]Handle1Func, 200), make(map[int32]Handle2Func, 200)}
    h.init()
    return h
}

func (h *SvHandle) ServeTwoWayMessage(msg *rpcservice.ProtoRequest) (res *rpcservice.ProtoResponse, err error) {
    handle, ok := h.TwoWayFunc[msg.Type]
    if !ok {
        return nil, fmt.Errorf("No [%d] Rpc Func", msg.Type)
    }

    res = rpcservice.NewProtoResponse()
    res.Content, res.Ret = handle(msg.Content)
    res.Type = msg.Type

    return
}

func (h *SvHandle) ServeOneWayMessage(msg *rpcservice.ProtoRequest) (err error) {
    handle, ok := h.OneWayFunc[msg.Type]
    if !ok {
        return fmt.Errorf("No [%d] Rpc Func", msg.Type)
    }

    ret := handle(msg.Content)
    if ret != 0 {
        err = fmt.Errorf("Serve %d ErrCod %d", msg.Type, ret)
    }
    return
}

